package com.zhixi.controller;

import com.zhixi.common.R;
import com.zhixi.customAnnotations.Status;
import com.zhixi.mapper.TbUserMapper;
import com.zhixi.pojo.TbUser;
import com.zhixi.service.TbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

/**
 * @ClassName UserController
 * @Author zhangzhixi
 * @Description 用户Web接口
 * @Date 2022-8-6 22:17
 * @Version 1.0
 */
@RestController
@RequestMapping("user")
// 此注解，用于校验方法参数
@Validated
public class UserController {

    @Autowired
    private TbUserService userService;

    @Autowired
    TbUserMapper tbUserMapper;

    /**
     * 插入用户信息-接收表单参数
     *
     * @param form 用户信息表单
     * @return 插入结果
     */
    @PostMapping("/insertUser")
    public R<String> insertUser(@Validated TbUser form) {
        // 插入用户信息
        int result = userService.insertUser(form);
        return R.success(result > 0 ? "插入成功" : "插入失败");
    }

    /**
     * 获取用户信息-参数校验，需要在类上添加@Validated注解
     *
     * @param id 用户id
     * @return 用户信息
     */
    @GetMapping("/getUserById")
    public R<TbUser> getUser(@NotNull(message = "id不能为空") Long id) {
        // 获取用户信息
        TbUser user = tbUserMapper.selectById(id);
        return R.success(user);
    }

    /**
     * 自定义注解实现参数校验
     *
     * @param type 状态类型
     * @return 校验结果
     */
    @GetMapping("/customAnnotations")
    public R<String> customAnnotations(@Status(statusType = {"1", "2"})
                                       @NotBlank(message = "参数不能为空") String type) {
        return R.success("参数校验成功");
    }
}
